package com.atguigu.gmall.realtime.util

import java.util
import java.util.Properties

import io.searchbox.client.config.HttpClientConfig
import io.searchbox.client.{JestClient, JestClientFactory}
import io.searchbox.core.{Bulk, BulkResult, Index, Search, SearchResult}
import org.elasticsearch.index.query.{BoolQueryBuilder, MatchQueryBuilder, RangeQueryBuilder}
import org.elasticsearch.index.search.MatchQuery
import org.elasticsearch.search.builder.SearchSourceBuilder
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder

import scala.collection.mutable.ListBuffer

object MyEsUtil {

  def main(args: Array[String]): Unit = {
    search()
  }

  private val properties: Properties = PropertiesUtil.load("config.properties")

  private    var  factory:  JestClientFactory=null;

  def getClient:JestClient ={
    if(factory==null)build();
    factory.getObject

  }

  def  build(): Unit ={
    factory=new JestClientFactory
    factory.setHttpClientConfig(new HttpClientConfig.Builder(properties.getProperty("es.server") )
      .multiThreaded(true)
      .maxTotalConnection(20)
      .connTimeout(10000).readTimeout(10000).build())

  }

  def save(): Unit ={
      val jestClient: JestClient = getClient
    //创建写入的动作
      val movie = Movie("100","我和我的父辈")
      val today="20211101"
      val index: Index = new Index.Builder(movie).index("movie_test0609_"+today).`type`("_doc").id("100").build()
      jestClient.execute(index)
      jestClient.close()
  }

  //批量写入
  def bulkSave(sourceList: List[(String,Any)],indexName:String): Unit ={

    val jestClient: JestClient = getClient
    val bulkBuilder = new Bulk.Builder()

    for ((id ,source)  <- sourceList ) {
      val index : Index = new Index.Builder(source).index(indexName).`type`("_doc").id(id) .build()
      bulkBuilder.addAction(index)
    }
    val bulk: Bulk = bulkBuilder.build()
    val result: BulkResult = jestClient.execute(bulk)
    println(s"  成功保存到es中：共  ${result.getItems.size()} 条")
    jestClient.close()
  }


  // 根据 关键词 +条件  + 分页+高亮 显示结果
 def  search(): Unit ={
    val jestClient: JestClient = getClient
   //直接贴dsl
   val queryDSL=
     """
       |{
       |  "query": {
       |     "bool": {
       |       "must": [
       |          {"match": {
       |            "name": "red sea"
       |          }}
       |       ],
       |       "filter": [
       |         {"range": {
       |           "doubanScore": {
       |             "gte": 5
       |           }
       |         }}
       |       ]
       |     }
       |  },
       |  "from": 0
       |  , "size": 20
       |  , "highlight": {
       |    "fields": {"name":{}}
       |  }
       |}
       |
     """.stripMargin

   //通过工具类生成dsl
   val searchSourceBuilder = new SearchSourceBuilder()
   val boolQueryBuilder = new BoolQueryBuilder()
   boolQueryBuilder.must(new MatchQueryBuilder("name","red sea"))
   boolQueryBuilder.filter(new RangeQueryBuilder("doubanScore").gte(5))

   searchSourceBuilder.query(boolQueryBuilder)
   searchSourceBuilder.size(20)
   searchSourceBuilder.from(0)
   searchSourceBuilder.highlighter(new HighlightBuilder().field("name"))

   println(searchSourceBuilder.toString())
   val search = new Search.Builder(searchSourceBuilder.toString()).addIndex("movie0609").addType("_doc").build()
   // 2 执行查询
   val result: SearchResult = jestClient.execute(search)
   //3 处理查询结果
   val rslist: util.List[SearchResult#Hit[util.Map[String, Any], Void]] = result.getHits( classOf[util.Map[String,Any]])
    val list=new ListBuffer[util.Map[String, Any]]
   import collection.JavaConverters._
   for (hit <- rslist.asScala ) {
     list.append(hit.source)
   }
   println(list.mkString("\n"))
   jestClient.close()

 }



  case class Movie(id:String,movie_name:String)

}
